package com.app.brilliant.game.service.impl;
import com.app.brilliant.common.service.impl.BaseServiceImpl;
import com.app.brilliant.game.bean.BriPlan;
import com.app.brilliant.game.bean.BriUserPlan;
import com.app.brilliant.game.dto.UserPlanInfoDTO;
import com.app.brilliant.game.service.BriPlanService;
import com.app.brilliant.game.service.BriUserPlanService;
import com.app.brilliant.game.mapper.BriUserPlanMapper;
import com.app.brilliant.game.service.WxConfigService;
import com.app.brilliant.sign.constant.Constants;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;

/**
* @author GF
* @description 针对表【bri_user_plan】的数据库操作Service实现
* @createDate 2025-08-27 16:12:02
*/
@Service
public class BriUserPlanServiceImpl extends BaseServiceImpl<BriUserPlanMapper, BriUserPlan>
implements BriUserPlanService{
    @Autowired
    private BriPlanService briPlanService;
    @Autowired
    private WxConfigService wxConfigService;
    @Override
    public UserPlanInfoDTO getLatestPaidPlanInfo(Integer uid) {
        return baseMapper.getUserPlanInfo(uid);
    }



    @Override
    public void addDefaultPlanForUser(Integer uid) throws RuntimeException {
        // 查询默认计划（money为0的计划）
        BriPlan defaultPlan = briPlanService.getFirstPlanByMoney(BigDecimal.valueOf(0));
        if (defaultPlan == null) {
            throw new RuntimeException("未找到默认计划");
        }
        // 插入用户计划
        BriUserPlan userPlan = new BriUserPlan();
        userPlan.setUid(uid);
        userPlan.setPlanId(defaultPlan.getId());
        userPlan.setStartTime(new Date());
        String defaultKeepDay = wxConfigService.getConfigValue(Constants.NomalConfigKey.DefaultPlanKeepDay);
        defaultKeepDay = defaultKeepDay == null ? "7" : defaultKeepDay;
        userPlan.setEndTime(DateUtils.addDays(new Date(), Integer.parseInt(defaultKeepDay)));
        baseMapper.insert(userPlan);
    }

    @Override
    public BriUserPlan getByUserId(Long userId) {
        return baseMapper.selectOne(new QueryWrapper<BriUserPlan>()
                .eq("uid", userId)
                .orderByDesc("id")
                .last("LIMIT 1"));
    }
}
